package com.zytool.easyrestful.core;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zytool.easyrestful.core.condition.EntityExampleBuilder;
import com.zytool.easyrestful.core.utils.ClassUtil;
import lombok.Setter;
import org.springframework.data.domain.Pageable;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

public class GenericService<T extends GenericEntity> {

    @Setter
    private GenericMapper<T> genericMapper;

    public PageInfo<T> selectByPage(Pageable pageRequest, Map<String, String> params) {
        PageHelper.startPage(pageRequest.getPageNumber(), pageRequest.getPageSize());
        Example example = EntityExampleBuilder.build(getEntityClass(), params);
        return new PageInfo<>(genericMapper.selectByExample(example));
    }

    public List<T> queryList(Map<String, String> params) {
        Example example = EntityExampleBuilder.build(getEntityClass(), params);
        return genericMapper.selectByExample(example);
    }

    public T getById(int id) {
        return genericMapper.selectByPrimaryKey(id);
    }

    public int save(T entity) {
        if (entity.getId() > 0) {
            return genericMapper.updateEntity(entity);
        }
        return genericMapper.insertEntity(entity);
    }

    public int delete(T entity) {
        return genericMapper.deleteByPrimaryKey(entity.getId());
    }

    private Class getEntityClass() {
        return ClassUtil.getGenericClass(this.getClass());
    }
}
